package com.zuxia.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.zuxia.dao.IMessageDao;
import com.zuxia.entity.Admin;
import com.zuxia.entity.Message;import antlr.debug.MessageEvent;

@Repository("messageDao")
public class MessageDao implements IMessageDao {
	@Resource(name = "hibernateTemplate")
	private HibernateTemplate hibernateTemplate;

	@SuppressWarnings("unchecked")
	public List<Message> selectAll() {
		return (List<Message>) hibernateTemplate.find("FROM Message");
	}

	public int deleteMessage(Message message) {
		try {
			Message s = hibernateTemplate.get(message.getClass(), message.getMessage_id());
			hibernateTemplate.delete(s);
		} catch (Exception e) {
			System.out.println("删除失败！！！");
			return 0;
		}
		return 1;
	}

	/**
	 * 批量删除
	 */
	public void batchDelteMessage(String checks) {
		String[] split = checks.split(",");
		for (String s : split) {
			if (s != null && s != "") {
				hibernateTemplate.delete(hibernateTemplate.get(Message.class, Integer.parseInt(s)));
			}
		}
	}

	public Message selectId(int id) {
		return (Message) hibernateTemplate.get(Message.class, id);
	}

	public int saveMessage(Message message) {
		int i = 0;
		try {
			i = (int) hibernateTemplate.save(message);
		} catch (Exception e) {
			System.out.println("添加失败");
			return i;
		}
		return i;
	}

	@SuppressWarnings("unchecked")
	public List<Message> selectTime() {
		SessionFactory session = hibernateTemplate.getSessionFactory();
		Session openSession = session.openSession();
		SQLQuery createSQLQuery = openSession.createSQLQuery("SELECT * FROM message ORDER BY message_time desc");
		return createSQLQuery.list();
	}

	public void updateMessage(Message message) {
		Message m = hibernateTemplate.get(Message.class,message.getMessage_id());
		m.setMessage_name(message.getMessage_name());
		m.setMessage_phone(message.getMessage_phone());
		m.setMessage_text(message.getMessage_text());
		m.setMessage_reply(m.getMessage_reply());
		m.setMessage_state(message.getMessage_state());
		m.setMessage_time(message.getMessage_time());
		m.setMessage_answer(message.getMessage_answer());
		hibernateTemplate.saveOrUpdate(m);
	}
}
